package com.joysuch.wwyt.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.baidu.enums.BaiduCodeEnum;
import com.joysuch.wwyt.baidu.req.BaiduFace;
import com.joysuch.wwyt.baidu.req.BaiduSample;
import com.joysuch.wwyt.baidu.util.DzPrtqUtils;
import com.joysuch.wwyt.core.bean.BaseUserBean;
import com.joysuch.wwyt.core.bean.BaseUserFaceLogBean;
import com.joysuch.wwyt.core.bean.BaseUserFaceLogReqBean;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.entity.BaseUserFaceLog;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.mapper.BaseUserFaceLogMapper;
import com.joysuch.wwyt.core.mapper.BaseUserMapper;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.core.service.BaseImageRepositoryService;
import com.joysuch.wwyt.core.service.BaseUserFaceLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xsx
 * @version 1.0
 * @date 2023/3/14 17:08
 */
@Service
@Transactional
@Slf4j
public class BaseUserFaceLogServiceImpl  extends ServiceImpl<BaseUserFaceLogMapper, BaseUserFaceLog> implements BaseUserFaceLogService {

    @Autowired
    private BaseUserMapper baseUserMapper;
    @Autowired
    private BaseConfigService baseConfigService;

    @Autowired
    private BaseImageRepositoryService baseImageRepositoryService;

    @Override
    public Page<BaseUserFaceLogBean> selectPage(BaseUserFaceLogReqBean bean) {
        Page<BaseUserFaceLogBean> page = new Page<>(bean.getPage() + 1, bean.getSize());
        Page<BaseUserFaceLogBean> beanPage = baseMapper.selectBeans(page, bean.getUserName(),bean.getSyncStartTime(),bean.getSyncEndTime());
        return beanPage;
    }

    @Override
    public void delete(Long id) {
        BaseUserFaceLog log = baseMapper.selectById(id);
        log.setDeleteFlag("1");
        baseMapper.updateById(log);
    }

    @Override
    public List<BaseUser> selectUsers() {
        return baseMapper.selectUsers();

    }



    @Override
    @Async
    public  void updateFace(List<BaseUserBean> userList){
        log.info("同步人员头像1--->");
        List<BaseUserFaceLog> logs=new ArrayList<>();
        String groupId =  getGroupId();
        for (BaseUserBean userBean : userList) {
            BaseUserFaceLog faceLog = new BaseUserFaceLog();
            try {
                faceLog.setSyncTime(new Date());
                faceLog.setUserId(userBean.getUserId());
                if (userBean.getIdCardImgId()==null) {
                    faceLog.setErrMsg("人脸照片不存在");
                    logs.add(faceLog);
                    continue;
                }
                String path = userBean.getPath();
                if (StringUtils.isBlank(path)) {
                    faceLog.setErrMsg("人脸照片不存在");
                    logs.add(faceLog);
                    continue;
                }
                log.info("请求前的路径"+path);
                String imageBase64 = DzPrtqUtils.readFileToBase64(new FileInputStream(path));
//                String orgCode=user.getOrgCode().replaceAll("-","_");
//                String groupId=user.getTenentId()+"_"+orgCode
                JSONObject jsonObject = new BaiduFace().addUser(BaiduSample.client, imageBase64, "BASE64", groupId, userBean.getUserId().toString(), null);
                String errorCode = jsonObject.get("error_code").toString();
                log.info("百度返回信息---->"+jsonObject.toString());
                if (errorCode.equals("0")) {
                    JSONObject result = jsonObject.getJSONObject("result");
                    log.info("百度返回信息result---->" + result);
                    String faceToken = result.getString("face_token");
                    log.info("百度返回信息faceToken---->"+ faceToken);
                    BaseUser user = baseUserMapper.findByUserId(userBean.getUserId());
                    user.setFaceToken(faceToken);
                    baseUserMapper.updateById(user);
                    log.info("更新人脸facetoken结束---->"+ JSON.toJSONString(userBean));
                    faceLog.setErrMsg("成功");
                }else {
                    log.info("更新人脸errorCode---->"+ errorCode);
                    BaiduCodeEnum baiduCodeEnum = BaiduCodeEnum.find(errorCode);
                    faceLog.setErrMsg(baiduCodeEnum==null?"":baiduCodeEnum.getErrMsg());
                }
                faceLog.setCreateTime(new Date());
                faceLog.setErrCode(errorCode);
                faceLog.setDetail(jsonObject.toString());
                logs.add(faceLog);
                log.info("线程休眠1---->");
                //线程休眠3秒
                Thread.sleep(3000);
                log.info("休眠结束2---->");
            } catch (IOException e) {
                e.printStackTrace();
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        log.info("同步人员头像结束--->");
        this.saveBatch(logs);
    }
    public String getGroupId(){
        String groupId="";
        BaseConfig groupIdConfig = baseConfigService.findFirstConfig(BaseConfigCodes.LOCATE_CURRENT_BUILD_ID);
        if (groupIdConfig!=null&&StringUtils.isNotBlank(groupIdConfig.getValue())){
            groupId= groupIdConfig.getValue();
        }
        return groupId;
    }
}
